/* eslint-disable no-template-curly-in-string */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { message, Button, Breadcrumb, Upload, Table, Divider, Modal, Form, Input, InputNumber, Select } from 'antd'
import $axios from '../../../http'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

export class UserList extends Component {
  state = {
    addVisible: false,
    editVisible: false,
    imageUrl: "", // 添加用户的头像
    editImageUrl: "", // 修改用户的头像
    loading: false, // 图片上传的加载状态
  };

  componentWillMount() {
    this.props.getUserList();
  }
  render() {
    let { user_list } = this.props;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '头像',
        key: 'profile',
        render: text =>
          <img style={{ width: '50px', height: '50px' }} src={text.profile} alt="" />
        ,
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
      },
      {
        title: '年龄',
        dataIndex: 'age',
        key: 'age',
      },
      {
        title: '角色',
        dataIndex: 'role',
        key: 'role',
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (

          <span>
            <a href="/">详情</a>
            <Divider type="vertical" />
            <Button type="link" onClick={() => {
              this.props.selectUser(record);
              this.setState({ editVisible: true })
            }}>修改</Button>
            <Divider type="vertical" />
            <a href="/">删除</a>
          </span>

        ),
      },
    ];

    const layout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const validateMessages = {
      required: '${label}不能为空',
      types: {
        email: '${label}不是一个合法的邮箱!',
        number: '${label}不是一个有效的数字',
      },
      number: {
        range: '${label}必须在${min}和${max}之间',
      },
    };
    const { Option } = Select;
    const { loading, imageUrl, editImageUrl } = this.state;

    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    function getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
    return (
      <div>
        <Breadcrumb style={{ margin: '16px 0' }}>
          <Breadcrumb.Item>首页</Breadcrumb.Item>
          <Breadcrumb.Item>用户管理</Breadcrumb.Item>
          <Breadcrumb.Item>用户列表</Breadcrumb.Item>
        </Breadcrumb>


        <p><Button type="primary" onClick={() => {
          this.setState({ addVisible: true });
        }}>添加用户</Button></p>

        <div>
          <Table columns={columns} dataSource={user_list} />
        </div>

        <Modal
          title="添加用户"
          visible={this.state.addVisible}
          footer={null}
          onCancel={() => {
            this.setState({ addVisible: false });
          }}
        >
          <p><Form {...layout} name="nest-messages" onFinish={(values) => {
            console.log('onFinsh values', values);
            values.profile = this.state.imageUrl;
            this.props.addUser(values);
            this.setState({ addVisible: false });
          }} validateMessages={validateMessages}>
            <Form.Item
              name='name'
              label="姓名"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item name="profile" label="头像">

              <Upload
                name="uploadFile"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                beforeUpload={(file) => {
                  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                  if (!isJpgOrPng) {
                    message.error('你只能上传 JPG/PNG 格式的文件!');
                  }
                  const isLt2M = file.size / 1024 / 1024 < 2;
                  if (!isLt2M) {
                    message.error('图片不能小于 2MB!');
                  }
                  return isJpgOrPng && isLt2M;
                }}
                onChange={(info) => {
                  console.log('onCHnage info', info);

                  if (info.file.status === 'uploading') {
                    this.setState({ loading: true });
                    return;
                  }
                  if (info.file.status === 'done') {
                    // Get this url from response in real world.
                    getBase64(info.file.originFileObj, imageUrl =>
                      this.setState({
                        imageUrl,
                        loading: false,
                      }),
                    );
                  }
                }}
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>

            </Form.Item>
            <Form.Item
              name="email"
              label="Email"
              rules={[
                {
                  required: true,
                  type: 'email',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="age"
              label="年龄"
              rules={[
                {
                  required: true,
                  type: 'number',
                  min: 0,
                  max: 99,
                },
              ]}
            >
              <InputNumber />
            </Form.Item>
            <Form.Item name="sex" label="性别" rules={[
              {
                required: true

              },
            ]}>
              <Select

              >
                <Option value="男">男</Option>
                <Option value="女">女</Option>
              </Select>
            </Form.Item>

            <Form.Item name="role" label="角色" rules={[
              {
                required: true

              },
            ]}>
              <Select

              >
                <Option value="运维">运维</Option>
                <Option value="市场">市场</Option>
                <Option value="销售">销售</Option>
                <Option value="开发">开发</Option>
              </Select>
            </Form.Item>
            <Form.Item name="introducation" label="自我介绍">
              <Input.TextArea />
            </Form.Item>
            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
              <Button type="primary" htmlType="submit">
                添加用户
        </Button>
            </Form.Item>
          </Form></p>

        </Modal>


        <Modal
          title="修改用户"
          visible={this.state.editVisible}
          footer={null}
          onCancel={() => {
            this.setState({ editVisible: false });
          }}
          destroyOnClose
        >
          <p>
            <Form {...layout} name="nest-messages" onFinish={(values) => {
              console.log('onFinsh editUser values', values);
              values.profile = this.state.editImageUrl;
              this.props.editUser(values);
              this.setState({ editVisible: false });
            }} validateMessages={validateMessages} initialValues={this.props.select_user}>
              <Form.Item
                name='id'
                label="编号"
                hidden

              >
                <Input />
              </Form.Item>
              <Form.Item
                name='name'
                label="姓名"
                rules={[
                  {
                    required: true,
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item name="profile" label="头像">

                <Upload
                  name="uploadFile"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  beforeUpload={(file) => {
                    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                    if (!isJpgOrPng) {
                      message.error('你只能上传 JPG/PNG 格式的文件!');
                    }
                    const isLt2M = file.size / 1024 / 1024 < 2;
                    if (!isLt2M) {
                      message.error('图片不能小于 2MB!');
                    }
                    return isJpgOrPng && isLt2M;
                  }}
                  onChange={(info) => {
                    console.log('onchinage info', info);

                    if (info.file.status === 'uploading') {
                      this.setState({ loading: true });
                      return;
                    }
                    if (info.file.status === 'done') {
                      // Get this url from response in real world.
                      getBase64(info.file.originFileObj, editImageUrl =>
                        this.setState({
                          editImageUrl,
                          loading: false,
                        }),
                      );
                    }
                  }}
                >
                  {editImageUrl || this.props.select_user.profile ? <img src={editImageUrl || this.props.select_user.profile} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>

              </Form.Item>
              <Form.Item
                name="email"
                label="Email"
                rules={[
                  {
                    required: true,
                    type: 'email',
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="age"
                label="年龄"
                rules={[
                  {
                    required: true,
                    type: 'number',
                    min: 0,
                    max: 99,
                  },
                ]}
              >
                <InputNumber />
              </Form.Item>
              <Form.Item name="sex" label="性别" rules={[
                {
                  required: true

                },
              ]}>
                <Select

                >
                  <Option value="男">男</Option>
                  <Option value="女">女</Option>
                </Select>
              </Form.Item>

              <Form.Item name="role" label="角色" rules={[
                {
                  required: true

                },
              ]}>
                <Select

                >
                  <Option value="运维">运维</Option>
                  <Option value="市场">市场</Option>
                  <Option value="销售">销售</Option>
                  <Option value="开发">开发</Option>
                </Select>
              </Form.Item>
              <Form.Item name="introducation" label="自我介绍">
                <Input.TextArea />
              </Form.Item>
              <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                <Button type="primary" htmlType="submit">
                  修改用户
        </Button>
              </Form.Item>
            </Form>
          </p>

        </Modal>

      </div>
    )
  }
}

const mapStateToProps = (state) => ({
  ...state
})

const mapDispatchToProps = (dispatch) => {
  return {
    getUserList() {
      dispatch(() => {
        $axios.get('/api/user/list').then((res) => {
          console.log('getUserList res', res);
          dispatch({ type: "SET_USER_LIST", data: res.user_list });
        })
      })
    },
    addUser(user) {
      dispatch({ type: "ADD_USER", data: user })
    },
    editUser(user) {
      dispatch({ type: "EDIT_USER", data: user })
    },
    selectUser(user) {
      dispatch({ type: "SELECT_USER", data: user })
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(UserList)
